package com.chaopei.day38.controlller;

import com.chaopei.day38.entity.Product;
import com.chaopei.day38.service.ProductService;
import com.chaopei.day38.service.UserService;
import com.chaopei.day38.utils.MyHtml;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Corday 天涯
 * @Date 2022/4/22 14:45
 * 已做了nginx代理,直接调用http://localhost/
 */
@Controller
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private ProductService productService;
//    注入静态化工具
    @Resource
    private MyHtml myHtml;

    //1.打开登录页http://localhost/login.html
    @RequestMapping("/login.html")
    public String login() {
        return "pages/login";
    }

    //2.执行登录并浏览商品
    @RequestMapping("/display.html")
    //@RequestMapping/get/post/put/delete;@RequestParam
    //@ResponseBody,这里静态化不能用session传参,因为静态后的网页没有session
    public String doLogin(String username,String password, Model model) {
        boolean flag = userService.login(username, password);
        List<Product> list = new ArrayList<>();
        //保存用户名与商品集合对象,为了一起做静态化处理
        Map maps =new HashMap();
        if (flag) {
            list = productService.queryProducts();
            maps.put("products",list);
            maps.put("username",username);
            //用户名与商品信息一起做静态化处理
            model.addAttribute("maps",maps);
            myHtml.createHtml("maps",maps,"display");
            return "pages/display";
        }
        //返回登录页
        model.addAttribute("error","用户名密码有误!");
        return "pages/login";
    }
}
